
N=500;
tol=0.0001 ;

beneficio = zeros(1,N);
means = zeros(1,N);
vars = zeros(1,N);

varianza = zeros(1,N);
cutValue = N;

for i=2:N
  var=parte2a(i); 	%devuelve un vector con [promedio varianza] para esa simulacion

  beneficio(i) = var(1);
  varianza(i) = var(2);
  
  means(i) = means(i-1) + ( beneficio(i) - means(i-1)) / i ; 
  vars(i) = vars(i-1) + (beneficio(i) - means(i-1))*(beneficio(i) - means(i));
  %varianza(i)=asimilar_varianza( mean(means(1:(i-1))),means(1:(i-1)),i-1);
  varianza(i) = vars(i) / (i-1);
  

  if( abs(varianza(i)-varianza(i-1)) < tol )
      cutValue = i
      break;
  end
end

%disp('variance values:');
%disp(varianza');

disp('result:');
fprintf('number of iteration steps (cut value): %d\n\n', cutValue);
fprintf('last variance value: %f\n\n', varianza(i));


%% plot the mean and the variance of the monthly benefit:
cDarkGrey = [0.3, 0.3, 0.3];
iStdSize = 12;

% mean of the monthly benefit:
% (don't use, return a wrong result!! --> use parte2b.m) 
% figure(7);
% clf;
% plot(1:cutValue, means(1:cutValue), '-', 'Color', cDarkGrey);
% 
% xlbl = xlabel('\it Numero de realizaciones n');
% ylbl = ylabel('\it Beneficio medio en un mes');
% set(xlbl, 'Interpreter', 'tex', 'FontName', 'Times', 'FontSize', iStdSize);
% set(ylbl, 'Interpreter', 'tex', 'FontName', 'Times', 'FontSize', iStdSize);

% variance of the monthly benefit:
figure(8);
clf;
plot(1:cutValue,varianza(1:cutValue),'-','Color',cDarkGrey);

xlbl = xlabel('\it Numero de realizaciones n');
ylbl = ylabel('\it Varianza del beneficio en un mes');
set(xlbl, 'Interpreter', 'tex', 'FontName', 'Times', 'FontSize', iStdSize);
set(ylbl, 'Interpreter', 'tex', 'FontName', 'Times', 'FontSize', iStdSize);
axis([0 500 0 5]);

% result:
% number of iteration steps (cut value): 500
% 
% last variance value: 0.130130

